package gis.toolkit;

import bean.common.Bts;
import bean.common.Cell;
import bean.common.RqCell;
import gis.algorithm.Extent;
import gis.algorithm.GeoPie;
import gis.algorithm.GeoPoint;
import gis.algorithm.GeoUtils;
import gis.algorithm.grid.GridUtils;
import gis.algorithm.grid.RqGridMap;
import gis.common.GisConfig;
import gis.core.utils.CSVUtils;
import gis.core.utils.CoreUtils;
import gis.dao.ResCellDao;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Xiaobing on 2016/12/5.
 */
public class CellToGrid {
    private String basePath = GisConfig.GetInstance().getBasePath();

    /**
     * 生成小区周围的 9*9的栅格  栅格规则为50*50
     */
    public void createCellGrid() {
        List<Cell> list = readCell();
        List<Cell> _list = new ArrayList<>();
        List<String> fs = new ArrayList<>();
        String content = "cell_key,cell_zhname,lac,ci,grid_id";
        fs.add(content);

        for (int i = 0; i < list.size(); i++) {
            Cell cell = list.get(i);
            double lon = cell.getLongitude() * 10000;
            double lat = cell.getLatitude() * 10000;
            for (int x = -4; x <= 4; x++) {
                for (int y = -4; y <= 4; y++) {
                    double _lon = (lon + x * 5) / 10000;
                    double _lat = (lat + y * 5) / 10000;
                    String id = GridUtils.getGridID(_lon, _lat);
                    content = cell.getId() + "," + cell.getName() + "," + cell.getLac() + "," + cell.getCi() + "," + id;
                    fs.add(content);
                }
            }
        }
        File file = new File(basePath + "cell_grid_id.csv");
        CSVUtils.exportCsv(file, fs);
    }

    /**
     * 小区栅格化 成20*20米的栅格
     */
    public void createCellTo20Grid() {
        int wkid = 4326;
        double radio = 400;
        int offest = 2;

        RqCell rqCell = new RqCell();
        rqCell.setGSM(true);
        int all = 0;

        ResCellDao resCellDao = new ResCellDao();
        try {

            List<String> list = new ArrayList<String>();

            String filePath = basePath + "/config/ads_f_area_dim_grid_2g_20.txt";
            File f = new File(filePath);
            if (f.exists()) {
                System.out.print("文件存在");
            } else {
                System.out.print("文件不存在");
                f.createNewFile();// 不存在则创建
            }
            BufferedWriter out = new BufferedWriter(new FileWriter(f));

            List<Bts> btses = resCellDao.GetBtsList(rqCell);
            //String test = "";
            for (Bts bts : btses) {
                for (Cell cell : bts.getCells()) {
                    //test = "";
                    Double y0 = cell.getLatitude();
                    Double x0 = cell.getLongitude();
                    GeoPoint centerPoint = new GeoPoint();
                    centerPoint.setX(x0);
                    centerPoint.setY(y0);
                    double startAngle = cell.getAzimuth() - cell.getAntbw();//开始角
                    double sweepAngle = cell.getAntbw() * 2.0;//覆盖角度
                    if (bts.getCells().size() == 1 && cell.getAzimuth() == 0) {
                        startAngle = 0;
                        sweepAngle = 360;
                    }

                    GeoPie pie = new GeoPie(centerPoint, radio, startAngle, sweepAngle, wkid);
                    List<GeoPoint> points = pie.getRingPoints();
                    Extent ex = pie.getRingExtent();

                    Double xMin = ex.getxMin();
                    Double xMax = ex.getxMax();
                    Double yMin = ex.getyMin();
                    Double yMax = ex.getyMax();
                    RqGridMap rqGridMap = GridUtils.getCommonGrid(xMin, yMin, offest);

                    int count = 0;
                    for (Double x = rqGridMap.getExtent().getxMin(); x <= xMax; x = (x * 10000 + offest) / 10000) {
                        for (Double y = rqGridMap.getExtent().getyMin(); y <= yMax; y = (y * 10000 + offest) / 10000) {
                            Double x1 = (x * 10000 + offest) / 10000;
                            Double y1 = (y * 10000 + offest) / 10000;
                            if (GeoUtils.isPointInPolygon(points, x, y)
                                    || GeoUtils.isPointInPolygon(points, x, y1)
                                    || GeoUtils.isPointInPolygon(points, x1, y)
                                    || GeoUtils.isPointInPolygon(points, x1, y1)) {

                                String gridId = GridUtils.getCommonGirdId(x, y, offest);

                                String str = gridId + "|" + x + "|"
                                        + x1 + "|" + y + "|"
                                        + y1 + "|" + cell.getLac() + cell.getCi() + "|"
                                        + cell.getName();
                                list.add(str);
                                //test += x + "," + y + ";" + x1 + "," + y1 + ";";
                                count++;
                                all++;
                            }
                        }
                    }

                    String rate = String.valueOf(1.0 / count);

                    for (String str : list) {
                        out.write(str + "|" + rate + "\r\n");
                    }

                    list.clear();
                }
            }

            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int a = 0;
    }

    /**
     * 读取小区信息
     *
     * @return
     */
    public List<Cell> readCell() {
        int count = 0;
        List<Cell> list = new ArrayList<>();
        String filePath = basePath + "config/2g.csv";
        InputStreamReader stream = null;
        BufferedReader reader = null;
        String line = null;

        try {
            stream = new InputStreamReader(new FileInputStream(filePath), "UTF-8");
            reader = new BufferedReader(stream);
            while ((line = reader.readLine()) != null) {
                if (count > 0) {
                    String[] arr = StringUtils.splitPreserveAllTokens(line, ",");
                    Cell cell = new Cell();
                    cell.setId(arr[0]);
                    cell.setLac(arr[1]);
                    cell.setCi(arr[2]);
                    cell.setName(arr[3]);
                    cell.setLongitude(Double.parseDouble(arr[4]));
                    cell.setLatitude(Double.parseDouble(arr[5]));
                    //cell.setAzimuth(Double.parseDouble(arr[6]));
                    list.add(cell);
                }
                count++;
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            CoreUtils.close(reader, stream);
        }
        return list;
    }


}
